package org.bycloud.common.util;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.bycloud.common.Digests;
import org.bycloud.common.Encodes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class EncryptUtils {

	private static EncryptUtils util;

	private EncryptUtils() {
		util = this;
	}

	@Value("${password.hashAlgorithm:sha-1}")
	private String hashAlgorithm;
	@Value("${password.hashIterations:1}")
	private int hashIterations;
	@Value("${password.saltSize:8}")
	private int saltSize;

	public static byte[] generateSalt() {
		return Digests.generateSalt(util.saltSize);
	}

	public static String entryptPassword(String plainPassword, byte[] salt) {
		String plain = Encodes.unescapeHtml(plainPassword);
		SimpleHash simpleHash = new SimpleHash(util.hashAlgorithm, plain.getBytes(), salt, util.hashIterations);
		if (log.isDebugEnabled()) {
			log.debug("hashAlgorithm is {}, hashIterations is {}, salt is {}, simpleHash is {}",
					new Object[] { util.hashAlgorithm, util.hashIterations, salt, simpleHash.toString() });
		}
		return Encodes.encodeHex(salt) + Encodes.encodeHex(simpleHash.getBytes());
	}
}
